﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
using System.Net.Sockets;

namespace B.S.BaseData.Read.API
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> logger;

        /// <summary>
        /// 构造方式注入
        /// </summary>
        /// <param name="logger"></param>
        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            this.logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
           var hostName=Dns.GetHostName();
           var hostEntry=Dns.GetHostEntry(hostName);
           var ipAddress=hostEntry.AddressList.FirstOrDefault(ip=>ip.AddressFamily==AddressFamily.InterNetwork);

            logger.LogError(ipAddress+context.Exception.StackTrace.Substring(0,50)+"发生了异常");
            context.ExceptionHandled = true;
        }
    }
}
